package com.stlm2.controller.user;

import com.google.gson.Gson;
import com.stlm2.core.base.BaseController;
import com.stlm2.core.common.md5.MD5;
import com.stlm2.dems.entity.User;
import com.stlm2.dems.user.entity.UserState;
import com.stlm2.dems.user.service.RoleService;
import com.stlm2.dems.service.UserService;
import com.stlm2.util.Memcached;
import com.stlm2.util.codecontent.CodeContent;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.util.*;

/**
 * Created by apple on 2017/5/30.
 */
@Controller
@RequestMapping("/userC")
public class UserController extends BaseController {
    @Resource
    private UserService userService;
    @Resource
    private Memcached memcached;

    @Resource
    private RoleService roleService;



   @ResponseBody
   @RequestMapping(value="/userLoginKey_V1.json",produces="application/json;charset=UTF-8")
    public String userLoginKey(String name, HttpServletRequest request, ModelMap model) throws UnsupportedEncodingException {

        if(StringUtils.isEmpty(name)){

            return  CodeContent.getModelByCode(0,"用户名不能为空",model);
        }
        String userName = new String(name.getBytes("iso-8859-1"), "UTF-8");
        String userKey;
        User user = userService.getByName(userName);
        if(user==null){
            return  CodeContent.getModelByCode(0,"用户名不存在",model);
        }
        userKey = user.getUserKey();
        model.put("userKey",userKey);

        return  CodeContent.getModelByCode(1,"",model);
    }
    @ResponseBody
    @RequestMapping(value="/crmLogin_V1.json",produces="application/json;charset=UTF-8")
    public String userLogin(ModelMap model, String userName, String passWord, HttpServletResponse response){
        response.setCharacterEncoding("UTF-8");
        Map<String,Object> map = new HashMap<String, Object>();
        if (org.apache.commons.lang.StringUtils.isBlank(userName) || org.apache.commons.lang.StringUtils.isBlank(passWord)) {

            return CodeContent.getModelByCode(0,"用户名密码不能为空", model);
        }
        //判断是否是合法的用户  begin
        User user = userService.getByName(userName.trim());
        if (user == null) {
            return CodeContent.getModelByCode(0,"用户名不正确", model);
        }


        String password2 = user.getPassword();
        //判断密码是否正确
        if (!passWord.equals(password2)) {
            return CodeContent.getModelByCode(0,"密码错误", model);
        }
        //判断是否是合法的用户  end
        if (UserState.Invalid.equals(user.getUserState())) {
            return CodeContent.getModelByCode(0,"手机号暂不可用", model);
        }

        //合法用户的操作：：：：：
        String	token = MD5.encryptMD5(user.getId() + user.getPassword() + new Date().toString());
        model.put("token", token);
        Gson gson = new Gson();
        model.put("realName",user.getRealName());
        model.put("userTypeValue",user.getUserTypeValue());
        model.put("userType",user.getUserType()!=null?user.getUserType().toString():"");
        memcached.set(token, 2*60*60, gson.toJson(user).toString()); //将对象和其token值存放在缓存中

        return CodeContent.getModelByCode(1,"sucess", model);

    }
    /*zlq
*查找后台用户列表页面
* */
    @ResponseBody
    @RequestMapping(value="/list",produces="application/json;charset=UTF-8")
    public ModelAndView index(ModelAndView modelAndView){

        modelAndView.setViewName("/userAdmin/userAdmin");
        return modelAndView;
    }

    	/*
	*查找后台用户列表
	* zlq
	*@param  token
	* @param userAccount:用户账号
	* @param  realName：名字
	* @param  userStateValue:用户状态值 1:正常  4 无效
	* @param  page:页码
	* @param  userTypeValue:用户类型值
	*
	 */
        @ResponseBody
        @RequestMapping(value="/getCRMUser.json",produces="application/json;charset=UTF-8")
        public String getCRMUser(ModelMap map ,String page,String token,String userAccount, String realName,String userStateValue,String userTypeValue){
            String data=null;
            try {
                data=userService.getCRMUser(map,page,token,userAccount,realName,userStateValue,userTypeValue);
            }catch (Exception e){
                e.printStackTrace();
                return CodeContent.returnFailure("搜索失败");
            }
            return  data;
        }

    	/*
	*创建后台用户
	* zlq
	* @param  token
	* @param  userAccount：新用户账号
	* @param  realName：新用户名字
	* @param  roleId：新用户角色ID
	* @param  phone:手机号
	 */
        @ResponseBody
        @RequestMapping(value="/addUser.json",produces="application/json;charset=UTF-8")
        public  String addUser(ModelMap map ,String token,String userAccount,String realName,String roleId,String phone,String companyCode){
            ModelMap data=null;
            try {
                data=userService.addUser(map,token,userAccount,realName,roleId,phone,companyCode);
            }catch (Exception e){
                e.printStackTrace();
                return CodeContent.returnFailure("添加失败");
            }
            return  new JSONObject(data).toString();

        }
	/*
	*对用户进行无效操作
	* zlq
	*@param  token
	* @param  id 用户id
	 */

    @ResponseBody
    @RequestMapping(value="/invalidUser.json",produces="application/json;charset=UTF-8")
    public  String invalidUser(ModelMap map ,String token,String id){
        String data=null;
        try {
            data=userService.invalidUser(map,token,id,UserState.Invalid);
        }catch (Exception e){
            e.printStackTrace();
            return CodeContent.returnFailure("操作失败");
        }
        return  data;
    }
    	/*
	*对用户进行有效操作
	* zlq
	*@param  token
	* @param  id 用户id
	 */
    @ResponseBody
    @RequestMapping(value="/normalUser.json",produces="application/json;charset=UTF-8")
    public  String normalUser(ModelMap map ,String token,String id){
        String data=null;
        try {
            data=userService.invalidUser(map,token,id,UserState.Normal);
        }catch (Exception e){
            e.printStackTrace();
            return CodeContent.returnFailure("操作失败");
        }
        return  data;
    }
    	/*
	*对用户进行角色修改
	* zlq
	*@param  token
	* @param  id 用户ID
	* @param roleId 角色ID
	 */
        @ResponseBody
        @RequestMapping(value="/updateUserRole.json",produces="application/json;charset=UTF-8")
        public  String updateUserRole(ModelMap map ,String token,String id,String roleId){
            String data=null;
            try {
                data=userService.updateUserRole(map,token,id,roleId);
            }catch (Exception e){
                e.printStackTrace();
                return CodeContent.returnFailure("操作失败");
            }
            return  data;
        }
    /*zlq
*查找后台用户修改登录密码页面
* */
    @ResponseBody
    @RequestMapping(value="/editPass",produces="application/json;charset=UTF-8")
    public ModelAndView editPass(ModelAndView modelAndView){

        modelAndView.setViewName("/editPass/editPass");
        return modelAndView;
    }
    /*
    *
    * zlq
    * CRM后台用户修改登录密码
    * @param  token
    * @param  password ：加密后的密码
    *
     */
    @ResponseBody
    @RequestMapping(value="/updateCRMPassword.json",produces="application/json;charset=UTF-8")
    public  String updateCRMPassword(ModelMap map ,String token,String password){
        String data=null;
        try {
            data=userService.updateCRMPassword(map,token,password);
        }catch (Exception e){
            e.printStackTrace();
            return CodeContent.returnFailure("修改登录密码失败");
        }
        return  data;
    }

    	/*
*
* zlq
* CRM后台用户初始化登录密码
* @param  token
* @param  id ：用户ID
*
 */
        @ResponseBody
        @RequestMapping(value="/initCRMPassword.json",produces="application/json;charset=UTF-8")
        public  String initCRMPassword(ModelMap map ,String token,String id){
            String data=null;
            try {
                data=userService.initCRMPassword(map,token,id);
            }catch (Exception e){
                e.printStackTrace();
                return CodeContent.returnFailure("修改登录密码失败");
            }
            return  data;
        }


    /*
*zlq
* crm获取查询后台成员下拉框
* token:
 */
    @ResponseBody
    @RequestMapping(value="/getInitRoleUserSelect.json",produces="application/json;charset=UTF-8")
    public  String getInitRoleUserSelect(ModelMap model,String token){
        String data=null;
        try {
            data=userService.getInitRoleUserSelect(model,token);
        }catch (Exception e){
            e.printStackTrace();
            return  CodeContent.getModelByCode(0,"查询失败",data);
        }
        return  data;
    }
}
